﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor.Operations
{
	internal class NewChunk : Operation
	{
        Engine.Selection Selected;
        Engine.Selection ItemAdded;
		Vector2 Position;
        Data.EntityRecord Entity;

        internal NewChunk(Engine.Selection Selected, Vector2 Position)
		{
			this.Selected = Selected;
			this.Position = Position;
		}

		internal override ReturnCode Do(EditorState ES)
		{
            Entity = ES.GetTopObject(Selected) as Data.EntityRecord;
            if (Entity == null) return ReturnCode.DoNotAddToUndoStack;

			Data.Chunk Chunk = new Data.Chunk();
			Chunk.Position = Position - ES.Map.Elements[Selected.TopIndex].GetPosition();
            float NewChunkScale = ES._config.NewChunkScale;
            if (NewChunkScale < 0.1f) NewChunkScale = 0.1f;
            Chunk.SetTexture(ES.SelectedTexture, ES.GetTexture(ES.SelectedTexture));
            Chunk.Scale = NewChunkScale;
           
			Chunk.Angle = 0;

			
			Entity.AttachedElements.Add(Chunk);

            ItemAdded = new Engine.Selection(Engine.Selection.Types.EntityElement, Selected.TopIndex,
				Entity.AttachedElements.Count - 1, 0);
            ES.RebuildNode(ItemAdded.TopIndex);

			ES.SelectItem(ItemAdded);

			return ReturnCode.AddToUndoStack;
		}

		internal override void Undo(EditorState ES)
		{
		    Entity.AttachedElements.RemoveAt(ItemAdded.MiddleIndex);
            ES.RebuildNode(ItemAdded.TopIndex);

            ES.SelectItem(new Engine.Selection(Engine.Selection.Types.MapElement, ItemAdded.TopIndex, 0, 0));
		}
	}
}
